package com.wxy.config;

import jakarta.annotation.PostConstruct;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 47868
 * 设置消息失败方法
 */
@Configuration
public class MqConfig {
    private static final Logger log = LoggerFactory.getLogger(MqConfig.class);
    private final RabbitTemplate rabbitTemplate;

    public MqConfig(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @PostConstruct
    public void init() {
        // 设置返回回调，处理消息路由失败的情况
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            log.error("监听到了消息return callback");
            log.debug("exchange: {}", returnedMessage.getExchange());
            log.debug("routingKey: {}", returnedMessage.getRoutingKey());
            log.debug("message: {}", returnedMessage.getMessage());
            log.debug("replyCode: {}", returnedMessage.getReplyCode());
            log.debug("replyText: {}", returnedMessage.getReplyText());
        });

        // 设置确认回调，处理消息发送到交换器的确认结果
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.debug("消息成功发送到交换器，ID: {}", correlationData.getId());
            } else {
                log.error("消息发送到交换器失败，ID: {}, 原因: {}", correlationData.getId(), cause);
            }
        });
    }
}
